<?php

namespace app\common\model;

use think\facade\Cache;

class OptionValue extends Base
{
    protected $table = 'option_values';
    public function getOptionEnameAttr($value, $data)
    {
        $option = Option::get(array('id' => $data['item_id']));
        if (empty($option)) {
            return '';
        }
        return $option->ename;
    }

    public function getChildCountAttr($value, $data)
    {
        return self::where('parent_id', $data['id'])->count();
    }

    public function getChildsAttr($value, $data)
    {
        return self::where('parent_id', $data['id'])->column('value');
    }

    //城市省份
    public function getProvinceLabelAttr($value, $data)
    {
        $parents = [];
        $option_value = OptionValue::where('value', $data['value'])->where('parent_id', '<>', 0)->find();
        if (!empty($option_value)) {
            $parents = $this->getParents(OptionValue::select()->toArray(), $option_value, 'id', 'parent_id', true);
            $parents = array_reverse($parents);
            $parents = array_column($parents, 'name');
        }
        $parents[] = $option_value['name'];
        if (empty($parents)) {
            return '';
        }
        $result = implode('', $parents);
        return $result;
    }
    //城市
    public  static function getCityAttr($value)
    {
        $cache_city='city';
        $isAlready = Cache::get($value.$cache_city);
        if ($isAlready) {
            return $isAlready;
        }
        $option_value = self::where(['name' => $value], ['parent_id', ['<>', 0]])->field("id,name,value as ve")->find();
        if ($option_value) {
            Cache::set($value.$cache_city, $option_value['ve'], 3600);
            return $option_value['ve'];
        }
        return 0;
    }
    //
    public  static function getvalueAttr($value)
    {
        // $isAlready = Cache::get($value);
        // if ($isAlready) {
        //     return $isAlready;
        // }
        // addLog($value,"ApiInfo");
        $option_value = OptionValue::where('name', $value)->where('parent_id', 0)->field("id,name,value as ve")->find();
        Cache::set($value, $option_value['ve'],3600);
        // addLog($option_value,"ApiInfo");

        return $option_value['ve'] ?? 0;
    }

       //获取cheng是对应的省份名称
       public  static function getProvinceNameAttr($value)
       {
           $option_value = self::where(['name' => $value], ['parent_id', ['<>', 0]])->field("id,parent_id,name,value as ve")->find();
           if ($option_value) {
            $parent_value = self::where(['id'=>$option_value['parent_id']])->field("id,parent_id,name,value as ve")->find();
            if($parent_value){
                return $parent_value['name'];
            }  
           }
           return "";
       }
}
